package com.tang.logger.pusher.databases;

import com.tang.logger.config.LogPusherProperties;
import com.tang.logger.domain.LogMessage;
import com.tang.logger.pusher.AbstractLogPusher;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @classname BufferedDatabaseLogPusher
 * @description [ 带缓冲区的 ]
 * @date 2021/7/25 21:20
 */
public class BufferedDatabaseLogPusher extends AbstractLogPusher implements DatabaseLogPusher{

    @Resource
    LogPusherProperties logPusherProperties;

    @Resource
    private JdbcService jdbcService;

    private int bufferIndex = 0;

    private int bufferSize = 100;

    private List<LogMessage> buffer;

    public BufferedDatabaseLogPusher(String namePrefix) {
        super(namePrefix);
    }

    @Override
    protected void push0(LogMessage logMessage) {
        buffer.add(logMessage);
        boolean isFull = this.bufferIndex++ >= this.bufferSize;
        if (isFull) {
            this.flush();
        }
    }

    private void flush() {
        jdbcService.insertBatch(this.buffer);
        this.buffer.clear();
        this.bufferIndex = 0;
    }

    @PostConstruct
    public void init() {
        this.bufferSize = this.logPusherProperties.getDatabase().getBufferSize();
        buffer = new ArrayList<>(10);
    }
}